package interview.algorithms.again_in_interview;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author fance
 * @date 2018/7/18 9:45
 */
public class LRULinkedHashMap<K,V> extends LinkedHashMap<K,V> {
    //定义缓存的容量
    private int capacity;

    public LRULinkedHashMap(int capacity) {
        super(capacity, 0.75f,true);
        this.capacity = capacity;
    }
    //实现LRU的关键方法，如果map里面的元素个数大于了缓存最大容量，则删除链表的顶端元素

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        System.out.println(eldest.getKey() + "=" + eldest.getValue());
        return size() > capacity;
    }

    public static void main(String[] args) throws Exception {

        //指定缓存最大容量为4
        Map<Integer,Integer> map=new LRULinkedHashMap<>(4);
        map.put(9,3);
        map.put(7,4);
        map.put(5,9);
        map.put(3,4);
        map.put(6,6);
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }

    }
}
